package com.oscar.ehome.view.loginview;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.oscar.ehome.R;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.pagebean.HdBean;
import com.oscar.ehome.bean.pagebean.SignNameBean;
import com.oscar.ehome.presenter.PagePresenter;
import com.oscar.ehome.provider.zxing.client.android.camera.CameraManager;
import com.oscar.ehome.provider.zxing.client.android.camera.open.SquareCameraContainer;
import com.oscar.ehome.provider.zxing.client.android.decode.BeepManager;
import com.oscar.ehome.provider.zxing.client.android.decode.CaptureActivityHandler;
import com.oscar.ehome.provider.zxing.client.android.decode.GoogleFaceDetect;
import com.oscar.ehome.provider.zxing.client.android.decode.InactivityTimer;
import com.oscar.ehome.provider.zxing.client.android.decode.SweepViewfinderView;
import com.oscar.ehome.provider.zxing.client.android.decode.ViewfinderView;
import com.oscar.ehome.provider.zxing.client.android.result.IdCardIdentify;
import com.oscar.ehome.provider.zxing.client.android.util.EventUtil;
import com.oscar.ehome.utils.imageview.ChuliPhoto;
import com.oscar.ehome.utils.selfdialog.SelfDialog;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.view.pageview.view.HdView;

import java.io.IOException;
import java.util.Collection;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by oscar
 * author: MengWanhe
 * date: On 2017/6/22
 * 扫描身份证页面
 */

public class CaptureActivity extends BasesActivity<HdView,PagePresenter> implements SurfaceHolder.Callback, HdView {

    //返回按钮
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    //返回
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    //标题
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    //全局
    @BindView(R.id.preview_view)
    SurfaceView previewView;
    /**
     * 闪光灯
     */
    @BindView(R.id.title_img_right)
    ImageView titleImgRight;
    /**
     * 闪光灯
     */
    @BindView(R.id.right_layout)
    RelativeLayout rightLayout;
    /**
     * 监控是否聚焦成功
     */
    @BindView(R.id.cameraContainer)
    SquareCameraContainer cameraContainer;
    //身份证扫描框
    @BindView(R.id.viewfinder_view)
    ViewfinderView viewfinderView;
    /**
     * 扫码页面布局
     */
    @BindView(R.id.sweepfinder_view)
    SweepViewfinderView viewfinderViews;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    /**
     * 相册
     */
    @BindView(R.id.home_tv_num)
    TextView homeTvNum;

    //相机配置页面
    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    public Camera c;
    private Result savedResultToShow;
    private boolean hasSurface;
    private Collection<BarcodeFormat> decodeFormats;
    private InactivityTimer inactivityTimer;
    private String characterSet;
    private BeepManager beepManager;
    static String scan_type;

    //是否打开闪光灯
    private boolean isFlashlightOpen;

    //人脸识别
    GoogleFaceDetect googleFaceDetect = null;
    private MainHandler mMainHandler = null;

    //活动签到
    private PagePresenter pagePresenter;
    String token = "";
    //是不是身份证扫描
    public int isIdcard = 0;
    private String smessage;
    private SelfDialog selfDialog;
    private int stop = 0;//是否关闭线程
    private int ISstop = 0;//是否关闭线程


    ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    SweepViewfinderView getViewfinderViews() {
        return viewfinderViews;
    }

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }


    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_arcodescan);
        ButterKnife.bind(this);
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(CaptureActivity.this).getSystemConfig().getColor()));
        initData();
        initView();
    }

    /***
     * 加载view
     */
    public void initView() {


        titleImgBack.setImageResource(R.mipmap.fanhui);

//        titleImgRight.setImageResource(R.mipmap.shan1);

        pagePresenter = new PagePresenter(this);

        isIdcard = getIntent().getIntExtra("isIdcard", 0);


        CommonUtils.isIdcard = isIdcard;
        if (isIdcard == 1) {//是身份证扫描展示身份证布局
            viewfinderView.setVisibility(View.VISIBLE);
            viewfinderViews.setVisibility(View.GONE);
            titleTopbar.setText(getString(R.string.idcarrd_approve));
            homeTvNum.setText("相册");
            homeTvNum.setVisibility(View.VISIBLE);
        } else if (isIdcard == 2) {//否则展示二维码布局
            viewfinderView.setVisibility(View.GONE);
            viewfinderViews.setVisibility(View.VISIBLE);
            titleTopbar.setText(getString(R.string.mine_sign_in));
        }
    }

    /**
     * 加载数据
     */
    public void initData() {
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        cameraContainer.bindActivity(this);
        token = SystemConfigFactory.getInstance(CaptureActivity.this).getSystemConfig().getToken();
    }


    @Override
    public void onResume() {
        super.onResume();
        cameraManager = new CameraManager(getApplication());
        if (isIdcard == 1) {//是身份证扫描展示身份证布局
            viewfinderView.setCameraManager(cameraManager, scan_type);
        } else {//是二维码扫描展示二维码布局
            viewfinderViews.setCameraManager(cameraManager, scan_type);
        }

        handler = null;
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        beepManager.updatePrefs();
        inactivityTimer.onResume();
    }

    @Override
    public void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
        }
        inactivityTimer.onPause();
        //cameraManager.closeDriver();
        if (!hasSurface) {
            SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            surfaceHolder.removeCallback(this);
        }
        handler = null;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected PagePresenter createPresenter() {
        pagePresenter = new PagePresenter(this);
        return pagePresenter;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (isIdcard == 1) {
                    if (stop == 0) {
                        stop = 1;
                        destoryAll();
                    }
                    Intent intrnt = new Intent(CaptureActivity.this, ApproveActivity.class);
                    startActivity(intrnt);
                    finish();
                } else {
                    destoryAll();
                    finish();
                }
                return super.onKeyDown(keyCode, event);
            case KeyEvent.KEYCODE_FOCUS:
            case KeyEvent.KEYCODE_CAMERA:
                // Handle these events so they don't launch the Camera app
                return true;
            // Use volume up/down to turn on light
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                cameraManager.setTorch(false);
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                cameraManager.setTorch(true);
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
        // Bitmap isn't used yet -- will be used soon
        if (handler == null) {
            savedResultToShow = result;
        } else {
            if (result != null) {
                savedResultToShow = result;
            }
            if (savedResultToShow != null) {
                Message message = Message.obtain(handler,
                        R.id.decode_succeeded, savedResultToShow);
                handler.sendMessage(message);
            }
            savedResultToShow = null;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder != null) {
            if (!hasSurface) {
                hasSurface = true;
                initCamera(holder);
            }
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    /**
     * 二维码信息返回
     *
     * @param rawResult
     * @param barcode
     */
    public void handleDecode(Result rawResult, Bitmap barcode) {

        stop = 1;
        inactivityTimer.onActivity();
        IdCardIdentify.saveBitmap(barcode, "barcode");
        destoryAll();
        boolean fromLiveScan = barcode != null;
        if (fromLiveScan) {
            beepManager.playBeepSoundAndVibrate();
            viewfinderViews.drawResultBitmap(barcode);
        }

        String qrCodetoken = SystemConfigFactory.getInstance(CaptureActivity.this).getSystemConfig().getToken();
        //userid
        String qrcodetext = rawResult.getText();

        //活动id
        String eventId = getIntent().getStringExtra("eventId");
        if (!TextUtils.isEmpty(qrcodetext)) {
            //        String token, String userId, String eventId
//            int leng=qrcodetext.length();
//            String L=qrcodetext.substring(0,leng/2).trim();
//            Log.d("changdu", "handleDecode: "+L);
            pagePresenter.saveEventSign(qrCodetoken, qrcodetext, eventId);
            showLoading();
        }
    }


    /**
     * 身份证信息返回
     *
     * @param rawResult
     * @param barcode
     */
    public void handleDecodeTwo(String rawResult, Bitmap barcode) {
        inactivityTimer.onActivity();
        stop = 1;
        if (ISstop == 0) {
            destoryAll();
        }
        ToastUtil.e("mwh", "身份证返回l");
        boolean fromLiveScan = barcode != null;
        if (fromLiveScan) {
            beepManager.playBeepSoundAndVibrate();
            viewfinderView.drawResultBitmap(barcode);
        }
        Intent intent = new Intent(CaptureActivity.this, SubmitActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 身份证信息返回
     *
     * @param rawResult
     */
    public void handleDecodeTwo(String rawResult) {
        inactivityTimer.onActivity();
        stop = 1;
        if (ISstop == 0) {
            destoryAll();
        }
        ToastUtil.e("mwh", "身份证返回l");
        Intent intent = new Intent(CaptureActivity.this, SubmitActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 结束的时候关闭所有
     */
    private void destoryAll() {
        ToastUtil.e("mwh", "结束所有");
        if (isIdcard == 1) {
            stopGoogleFaceDetect();
        }
        if (mMainHandler != null) {
            mMainHandler.removeCallbacksAndMessages(null);
        }
        if (handler != null) {
            handler.quitSynchronously();
        }
        if (cameraContainer != null) {
            cameraContainer.onStop();
        }
        inactivityTimer.shutdown();
        cameraManager.closeDriver();
        cameraManager.stopPreview();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }


    /**
     * Superimpose a line for 1D or dots for 2D to highlight the key features of
     * the barcode.
     *
     * @param barcode   A bitmap of the captured image.
     * @param rawResult The decoded results which contains the points to draw.
     */
    private void drawResultPoints(Bitmap barcode, Result rawResult) {
        ResultPoint[] points = rawResult.getResultPoints();
        if (points != null && points.length > 0) {
            Canvas canvas = new Canvas(barcode);
            Paint paint = new Paint();
            paint.setColor(getResources().getColor(R.color.result_points));
            if (points.length == 2) {
                paint.setStrokeWidth(4.0f);
                drawLine(canvas, paint, points[0], points[1]);
            } else if (points.length == 4
                    && (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A || rawResult
                    .getBarcodeFormat() == BarcodeFormat.EAN_13)) {
                // Hacky special case -- draw two lines, for the barcode and
                // metadata
                drawLine(canvas, paint, points[0], points[1]);
                drawLine(canvas, paint, points[2], points[3]);
            } else {
                paint.setStrokeWidth(10.0f);
                for (ResultPoint point : points) {
                    canvas.drawPoint(point.getX(), point.getY(), paint);
                }
            }
        }
    }

    private static void drawLine(Canvas canvas, Paint paint, ResultPoint a,
                                 ResultPoint b) {
        canvas.drawLine(a.getX(), a.getY(), b.getX(), b.getY(), paint);
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            if (handler == null) {
                if (isIdcard == 1) {//是身份证扫描展示身份证布局
                    handler = new CaptureActivityHandler(this, viewfinderView,
                            decodeFormats, characterSet, cameraManager, scan_type);
                } else {//是二维码扫描展示二维码布局
                    handler = new CaptureActivityHandler(this, viewfinderViews,
                            decodeFormats, characterSet, cameraManager, scan_type);
                }
            }
            decodeOrStoreSavedBitmap(null, null);
            //是扫描身份证的话才会开启人脸识别
            if (isIdcard == 1) {
                c = cameraManager.getCamera();
                mMainHandler = new MainHandler();
                googleFaceDetect = new GoogleFaceDetect(getApplicationContext(), mMainHandler);
//                立即做是没有效果的，必须加个延时。
                mMainHandler.sendEmptyMessageDelayed(EventUtil.CAMERA_HAS_STARTED_PREVIEW, 5000);
            }
        } catch (IOException ioe) {
            finish();
        } catch (RuntimeException e) {
        }
    }

    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
        }
    }

    public void drawViewfinder() {
        if (CommonUtils.isIdcard == 1) {
            viewfinderView.drawViewfinder();
        } else {
            viewfinderViews.drawViewfinder();
        }
    }

    private static final int CHOOSE_PIC = 0;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1 && requestCode == 6) {
            if (data != null) {
                String lujing = ChuliPhoto.getPhotoPath(this, data, 1);
                if (lujing != null) {
                    Bitmap bitmap = BitmapFactory.decodeFile(lujing);
                    IdCardIdentify.saveBitmap(bitmap, "idcardImage");
                    handleDecodeTwo(lujing);
                }
            }
        } else {
            handler = null;
            SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            if (hasSurface) {
                initCamera(surfaceHolder);
            } else {
                surfaceHolder.addCallback(CaptureActivity.this);
                surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            }
            beepManager.updatePrefs();
            inactivityTimer.onResume();
        }
    }


    /*
      身份证通过相册选择图片
     */
    private String parseIdCardBitmap(String bitmapPath) {
        // 获取到待解析的图片
        Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath);
        return IdCardIdentify.idCardIdentify(this, bitmap);
    }

    @OnClick({R.id.title_layout_left, R.id.right_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_layout_left:
                if (isIdcard == 1) {//身份证扫描
                    if (stop == 0) {
                        stop = 1;
                        destoryAll();
                    }
                    Intent intrnt = new Intent(CaptureActivity.this, ApproveActivity.class);
                    startActivity(intrnt);
                    finish();
                } else {//二维码扫描
                    destoryAll();
                    finish();
                }
                break;
            case R.id.right_layout:
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                if (stop == 0) {
                    destoryAll();
                    ISstop = 1;
                }
                startActivityForResult(intent, 6);
                break;
//            case R.id.photo:
//                //开启闪光灯时调用
//            if (isFlashlightOpen) {
//                titleImgRight.setImageResource(R.mipmap.shan1);
//                cameraManager.setTorch(false); // 关闭闪光灯
//                isFlashlightOpen = false;
//            } else {
//                titleImgRight.setImageResource(R.mipmap.shan2);
//                cameraManager.setTorch(true); // 打开闪光灯
//                isFlashlightOpen = true;
//            }
//                break;
        }
    }

    //实现接口未用到
    @Override
    public void getHdList(HdBean result) {

    }

    //活动签到
    @Override
    public void saveEventSign(SignNameBean baseBean) {
        //  ToastUtil.show(CaptureActivity.this, baseBean.getMessage());
        dismissLoading();
        smessage = baseBean.getMessage();

        if (baseBean.getSuccess().equals("1")) {

            selfDialog = new SelfDialog(this);
            selfDialog.setTitleimg(1);
            selfDialog.setMessage(baseBean.getObject().getName() + "签到成功");

            selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {

                    handler = null;
                    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
                    SurfaceHolder surfaceHolder = surfaceView.getHolder();
                    if (hasSurface) {
                        initCamera(surfaceHolder);
                    } else {
                        surfaceHolder.addCallback(CaptureActivity.this);
                        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
                    }
                    beepManager.updatePrefs();
                    inactivityTimer.onResume();
                    selfDialog.dismiss();
                }
            });
           /* selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    //  selfDialog.dismiss();
                }
            });*/
            selfDialog.show();

        } else {

            selfDialog = new SelfDialog(this);
            selfDialog.setTitleimg(2);
            selfDialog.setMessage("很抱歉签到失败！请重新扫描");
            selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {

                    handler = null;
                    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
                    SurfaceHolder surfaceHolder = surfaceView.getHolder();
                    if (hasSurface) {
                        initCamera(surfaceHolder);
                    } else {
                        surfaceHolder.addCallback(CaptureActivity.this);
                        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
                    }
                    beepManager.updatePrefs();
                    inactivityTimer.onResume();

                    selfDialog.dismiss();
                }
            });

            selfDialog.show();
        }
    }

    @Override
    public void erroy() {
        if (isIdcard == 1) {//是身份证扫描展示身份证布局
            dismissLoading();
        } else {
            dismissLoading();
            ToastUtil.show(CaptureActivity.this, "请求失败");
        }
    }

    @Override
    public void erry(String result) {
        if (isIdcard == 1) {//是身份证扫描展示身份证布局
            dismissLoading();
        } else {
            dismissLoading();
            selfDialog = new SelfDialog(this);
            selfDialog.setTitleimg(2);
            selfDialog.setMessage(result);

            selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {

                    handler = null;
                    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
                    SurfaceHolder surfaceHolder = surfaceView.getHolder();
                    if (hasSurface) {
                        initCamera(surfaceHolder);
                    } else {
                        surfaceHolder.addCallback(CaptureActivity.this);
                        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
                    }
                    beepManager.updatePrefs();
                    inactivityTimer.onResume();

                    selfDialog.dismiss();
                }
            });
            selfDialog.show();
        }

    }


    private class MainHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case EventUtil.UPDATE_FACE_RECT:
                    Camera.Face[] faces = (Camera.Face[]) msg.obj;
                    viewfinderView.setFaces(faces);
                    break;
                case EventUtil.CAMERA_HAS_STARTED_PREVIEW:
                    startGoogleFaceDetect();
                    break;
            }
            super.handleMessage(msg);
        }

    }

    private void startGoogleFaceDetect() {
        if (c != null) {
            Camera.Parameters params;
            try {
                if (c.getParameters() != null) {
                    params = c.getParameters();
                    if (params.getMaxNumDetectedFaces() > 0) {
                        if (viewfinderView != null) {
//                viewfinderView.clearFaces();
                            viewfinderView.setVisibility(View.VISIBLE);
                        }
                        cameraManager.getCamera().setFaceDetectionListener(googleFaceDetect);
                        cameraManager.getCamera().startFaceDetection();
                    }
                }
            } catch (RuntimeException e) {

            }
        }
    }

    public void stopGoogleFaceDetect() {
        Camera.Parameters params = null;
        if (c != null) {
            try {
                if (c.getParameters() != null) {
                    params = c.getParameters();
                    if (params.getMaxNumDetectedFaces() > 0) {
                        if (cameraManager != null && cameraManager.getCamera() != null) {
//                cameraManager.getCamera().setFaceDetectionListener(null);
                            cameraManager.getCamera().stopFaceDetection();
                            viewfinderView.clearFaces();
                        }
                    }
                }
            } catch (RuntimeException e) {

            }
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (cameraContainer != null) {
            cameraContainer.onStart();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (cameraContainer != null) {
            cameraContainer.onStop();
        }
    }

}
